/**
 * useSparkCreation Hook
 * 提供Spark创作状态和操作的访问接口
 */

import { useContext } from 'react'
import { SparkCreationContext } from './SparkCreationProvider'
import { SparkCreationContextValue } from './types'

/**
 * 使用Spark创作状态的Hook
 */
export function useSparkCreation(): SparkCreationContextValue {
  const context = useContext(SparkCreationContext)
  
  if (context === undefined) {
    throw new Error('useSparkCreation必须在SparkCreationProvider内部使用')
  }
  
  return context
}

/**
 * 检查Spark创作是否可用
 */
export function useSparkCreationAvailable(): boolean {
  try {
    const { state } = useSparkCreation()
    return !state.error || state.error.code !== 'api_key_missing'
  } catch {
    return false
  }
}

/**
 * 获取创作进度信息
 */
export function useSparkCreationProgress() {
  const { state } = useSparkCreation()
  
  if (!state.currentOutline) {
    return {
      progress: 0,
      currentStep: '准备中',
      totalSections: 0,
      completedSections: 0
    }
  }

  const totalSections = state.currentOutline.sections.length
  const completedSections = state.currentOutline.sections.filter(
    section => section.status === 'completed'
  ).length
  
  const progress = totalSections > 0 ? Math.round((completedSections / totalSections) * 100) : 0
  
  let currentStep = '准备中'
  if (state.isGenerating) {
    currentStep = '正在生成内容'
  } else if (state.currentDialogStep) {
    currentStep = '对话引导中'
  } else if (progress === 100) {
    currentStep = '创作完成'
  } else if (state.currentOutline) {
    currentStep = '等待生成'
  }

  return {
    progress,
    currentStep,
    totalSections,
    completedSections
  }
}